import type { FC } from 'react';
import { useRef } from 'react';
import Tools, { type ToolsRef } from './tools';
import * as helper from './helper';
import useEvent from '../hooks/useEvent';
import useEditor from '../hooks/useEditor';
import { useSafeState, useMemoizedFn } from 'ahooks';
import type { MultiToolResult } from '../MultiTool/types';

import styles from './styles.module.less';

const LeftBar: FC = () => {
  const [editor] = useEditor();
  const dConfs = editor.defaultConfigs;
  const toolRefs = useRef<ToolsRef>(null);
  const initFill = dConfs.initFill.color;
  const initStroke = dConfs.initStroke.color;
  const [fill, setFill] = useSafeState<string>(initFill);
  const [stroke, setStroke] = useSafeState<string>(initStroke);

  // 切换不同的工具
  const onToolChange = useMemoizedFn((tool: MultiToolResult) => {
    const { current, child } = tool;
    const mode = current.id;

    switch (mode) {
      case 'shapelib': {
        let path = current.path;
        if (child) {
          path = child.selectedItem.path;
        }
        if (path) {
          helper.setShapePath(editor, path);
        }
      }
      default: {
        const curMode = editor.getMode();
        if (curMode !== mode) {
          editor.setMode(mode);
        }
      }
    }
  });

  //选中一个元素
  const onSingleSelected = useMemoizedFn((ele: Element) => {
    const attrs = ['fill', 'stroke'];
    const [fill, stroke] = helper.getElementColor(ele, attrs);
    setFill(fill);
    setStroke(stroke);
  });

  const onElementsSelected = useMemoizedFn((eles: Element[], mode: string) => {
    editor.textInputClear();
    switch (mode) {
      case 'select':
      case 'multiselect': {
        toolRefs.current?.resetTool();
        if (eles.length === 1) {
          onSingleSelected(eles[0]);
        }
        break;
      }
    }
  });

  //设置选中元素的填充颜色
  const setElementFill = useMemoizedFn((color: string) => {
    setStroke(color);
    helper.setEditorFillColor(editor, color);
  });

  //设置选中元素的边框颜色
  const setElementStroke = useMemoizedFn((color: string) => {
    setFill(color);
    helper.setEditorStrokeColor(editor, color);
  });

  useEvent("selected", onElementsSelected);

  return (
    <div className={styles.tools}>
      <Tools
        fill={fill}
        ref={toolRefs}
        stroke={stroke}
        onToolChange={onToolChange}
        onFillChange={setElementFill}
        onStrokeChange={setElementStroke}
      />
    </div>
  );
}

export default LeftBar;